<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="型号" prop="itemModel">
        <el-input
            v-model="queryParams.itemModel"
            placeholder="请输入型号"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="区域" prop="area">
        <el-input
            v-model="queryParams.area"
            placeholder="请输入区域"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="名称" prop="itemName">
        <el-input
            v-model="queryParams.itemName"
            placeholder="请输入名称"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="产品类型" prop="itemType">
        <el-tree-select
            v-model="queryParams.itemType"
            :data="typeOptions"
            :props="{ value: 'itemTypeId', label: 'typeName', children: 'children' }"
            value-key="itemTypeId"
            placeholder="请选择产品类型"
            check-strictly
        />
      </el-form-item>

      <el-form-item label="零售价" prop="retailPrice">
        <el-input-number v-model="queryParams.params.retailPriceStart" :min="1"
                         :max="queryParams.params.retailPriceEnd - 1"/>
        <el-input-number v-model="queryParams.params.retailPriceEnd" :min="queryParams.params.retailPriceStart + 1"/>
      </el-form-item>

      <el-form-item label="供应商" prop="supplier">
        <el-input
            v-model="queryParams.supplier"
            placeholder="请输入供应商"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="规格" prop="specification">
        <el-input
            v-model="queryParams.specification"
            placeholder="请输入规格"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="颜色" prop="color">
        <el-input
            v-model="queryParams.color"
            placeholder="请输入颜色"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单位" prop="unit">
        <el-input
            v-model="queryParams.unit"
            placeholder="请输入单位"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:item:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:item:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:item:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="Upload"
            @click="handleImport"
            v-hasPermi="['system:item:import']"
        >产品信息导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="Upload"
            @click="imghandleImport"
            v-hasPermi="['system:item:import']"
        >产品图片导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['system:item:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="itemList" height="550" scrollbar-always-on
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="产品图片" align="center" prop="imgUrl" width="100">
        <template #default="scope">
          <el-image
              style="width: 50px; height: 50px"
              :src="scope.row.imgUrl"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="[scope.row.imgUrl]"
              :initial-index="4"
              fit="cover"
              preview-teleported
          />
        </template>
      </el-table-column>
      <el-table-column label="型号" align="center" prop="itemModel"/>
      <el-table-column label="名称" align="center" prop="itemName"/>
      <el-table-column label="分类" align="center" prop="basItemType.typeName"/>
      <el-table-column label="尺寸" align="center" prop="specification"/>
      <el-table-column label="颜色" align="center" prop="color" show-overflow-tooltip/>
      <el-table-column label="材质" align="center" prop="texture" show-overflow-tooltip/>
      <el-table-column label="单位" align="center" prop="unit"/>
      <el-table-column label="区域" align="center" prop="area"/>
      <el-table-column label="供应商" align="center" prop="supplier"/>
      <el-table-column label="出厂价" align="center" prop="purchasePrice"/>
      <el-table-column label="零售价" align="center" prop="retailPrice"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:item:edit']">
            修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:item:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <!-- 添加或修改产品信息对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="itemRef" inline :model="form" :rules="rules" label-width="120px">
        <el-form-item label="产品图片" prop="imgUrl" size="small">
          <el-image
              :src="form.imgUrl"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="[form.imgUrl]"
              style="width: 150px; height: 150px"/>
        </el-form-item>
        <el-form-item label="型号" prop="itemModel">
          <el-input v-model="form.itemModel" placeholder="请输入型号"/>
        </el-form-item>
        <el-form-item label="类型" prop="itemType">
          <el-tree-select
              v-model="form.itemType"
              :data="typeOptions"
              :props="{ value: 'itemTypeId', label: 'typeName', children: 'children' }"
              value-key="itemTypeId"
              placeholder="请选择产品类型"
              check-strictly
          />
        </el-form-item>
        <el-form-item label="名称" prop="itemName">
          <el-input v-model="form.itemName" placeholder="请输入名称"/>
        </el-form-item>

        <el-form-item label="规格" prop="specification">
          <el-input v-model="form.specification" placeholder="请输入规格"/>
        </el-form-item>
        <el-form-item label="颜色" prop="color">
          <el-input v-model="form.color" placeholder="请输入颜色"/>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位"/>
        </el-form-item>
        <el-form-item label="区域" prop="area">
          <el-input v-model="form.area" placeholder="请输入区域"/>
        </el-form-item>
        <el-form-item label="供应商" prop="supplier">
          <el-input v-model="form.supplier" placeholder="请输入供应商"/>
        </el-form-item>
        <el-form-item label="出厂价" prop="purchasePrice">
          <el-input-number v-model="form.purchasePrice" :min="0" precision="2" placeholder="请输入出厂价"/>
        </el-form-item>
        <el-form-item label="零售价" prop="retailPrice">
          <el-input-number v-model="form.retailPrice" :min="0" precision="2" placeholder="请输入零售价"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 产品导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?updateSupport=' + upload.updateSupport"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
      >
        <el-icon class="el-icon--upload">
          <upload-filled/>
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport"/>
              是否更新已经存在的产品数据
            </div>
            <span>仅允许导入xls、xlsx格式文件，文件大小不超过200M。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                     @click="importTemplate">下载模板
            </el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 产品图片导入对话框 -->
    <el-dialog :title="imgupload.title" v-model="imgupload.open" width="400px" append-to-body>
      <el-upload
          ref="imguploadRef"
          accept=".zip"
          :limit=1
          :headers="imgupload.headers"
          :action="imgupload.url"
          :disabled="imgupload.isUploading"
          :on-progress="imghandleFileUploadProgress"
          :on-success="imghandleFileSuccess"
          :auto-upload="false"
          drag
      >
        <el-icon class="el-icon--upload">
          <upload-filled/>
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许 zip压缩文件。</span>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="imgsubmitFileForm">确 定</el-button>
          <el-button @click="imgupload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup name="Item">
import {listItem, getItem, delItem, addItem, updateItem} from "@/api/system/item";
import {listType} from "@/api/system/itemType.js";
import {getToken} from "@/utils/auth";

const {proxy} = getCurrentInstance();

const itemList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

/*** 产品导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: {Authorization: "Bearer " + getToken()},
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/item/importData"
});

/** 产品图片 */
const imgupload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: {Authorization: "Bearer " + getToken()},
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/item/importImg"
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    itemModel: null,
    itemName: null,
    supplier: null,
    specification: null,
    color: null,
    area: null,
    itemType: null,
    unit: null,
    imgUrl: null,
    retailPrice: null,
    params: {}
  },
  rules: {
    itemModel: [
      {required: true, message: "型号不能为空", trigger: "blur"}
    ],
    itemType: [
      {required: true, message: "类型不能为空", trigger: "blur"}
    ],
    specification: [
      {required: true, message: "规格不能为空", trigger: "blur"}
    ],
    itemName: [
      {required: true, message: "名称不能为空", trigger: "blur"}
    ],
    retailPrice: [
      {required: true, message: "零售价不能为空", trigger: "blur"},
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);
const typeOptions = ref(undefined);

/** 查询产品类型下拉树结构 */
function getTreeselect() {
  listType().then(response => {
    typeOptions.value = [];
    typeOptions.value = proxy.handleTree(response.data, "itemTypeId", "parentId");
  });
}

/** 查询产品信息列表 */
function getList() {
  loading.value = true;
  listItem(queryParams.value).then(response => {
    itemList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}


/** 导入图片按钮操作 */
function imghandleImport() {
  imgupload.title = "产品图片导入";
  imgupload.open = true;
};

/**图片上传中处理 */
const imghandleFileUploadProgress = (event, file, fileList) => {
  imgupload.isUploading = true;
};
/** 图片上传成功处理 */
const imghandleFileSuccess = (response, file, fileList) => {
  imgupload.open = false;
  imgupload.isUploading = false;
  proxy.$refs["imguploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
  getList();
};

/** 提交上传文件 */
function imgsubmitFileForm() {
  proxy.$refs["imguploadRef"].submit();
};


/** 导入按钮操作 */
function handleImport() {
  upload.title = "产品信息导入";
  upload.open = true;
};

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    itemId: null,
    itemModel: null,
    itemName: null,
    supplier: null,
    specification: null,
    color: null,
    area: null,
    itemType: null,
    unit: null,
    imgUrl: null,
    retailPrice: null,
    productionDate: null,
    expiryDate: null,
    delFlag: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("itemRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.params = {}
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.itemId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
async function handleAdd() {
  reset();
  await getTreeselect();
  open.value = true;
  title.value = "添加产品信息";
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  await getTreeselect();
  const _itemId = row.itemId || ids.value
  getItem(_itemId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改产品信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["itemRef"].validate(valid => {
    if (valid) {
      if (form.value.itemId != null) {
        updateItem(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addItem(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _itemIds = row.itemId || ids.value;
  proxy.$modal.confirm('是否确认删除产品信息编号为"' + _itemIds + '"的数据项？').then(function () {
    return delItem(_itemIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/item/export', {
    ...queryParams.value
  }, `item_${new Date().getTime()}.xlsx`)
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download("system/item/importTemplate", {}, `产品导入模板_${new Date().getTime()}.xlsx`);
};

getList();
getTreeselect();
</script>
